<?php


namespace app\engine\controller;


use cmf\controller\HomeBaseController;
use think\Db;

class ContactController extends HomeBaseController
{
    public function index()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $res = Db::name('contact')->where(['eid' => $id])->order('createTime desc')->select();
        foreach ($res as $k => &$v) {
            $v['img'] = 'http://' . $_SERVER['SERVER_NAME'] . $v['img'];
        }
        $this->assign('res', $res);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function add()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 3){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $id = $data['id'];
        $this->assign('id', $id);
        return $this->fetch();
    }

    /**
     * 执行添加
     */
    public function doadd()
    {
        $data = $this->request->param();
        $files = $this->request->file('img');
        if (empty($data['subTime'])) {
            $this->error('请选择送审时间');
        }
        if (empty($data['title'])) {
            $this->error('请填写联系单名称');
        }
        if (empty($data['desc'])) {
            $this->error('请填写描述');
        }
        if (empty($data['status'])) {
            $this->error('请选择流程完成情况');
        }
        if (empty($files)) {
            $this->error('请添加图片');
        }
        $data['createTime'] = time();
        foreach ($files as $k => $file) {
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
            if ($info) {
                $kps[$k] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
            } else {
                $this->error($file->getError());
            }
        }
        $data['img'] = implode(',', $kps);

//        if ($file) {
//            $info = $file->move(CMF_ROOT . 'public' . '/' . 'uploads');
//            if ($info) {
//                // 成功上传后 获取上传信息
//                $data['img'] = '/uploads/' . date('Ymd', time()) . '/' . $info->getFilename();
//            } else {
//                $this->error($info->getError());
//            }
//        }

        $res = Db::name('contact')->insert($data);
        if (!$res) {
            $this->error('添加失败');
        }
        $this->success('添加成功');
    }

    public function del()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 3){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $res = Db::name('contact')->where(['id' => $data['id']])->delete();
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function see()
    {
        $data = $this->request->param();
        $res = Db::name('contact')->where(['id' => $data['id']])->find();
        $res['img'] = explode(',', $res['img']);
        foreach ($res['img'] as $k => &$v) {
            $v = 'http://' . $_SERVER['SERVER_NAME'] . $v;
        }
        $this->assign('res', $res);
        return $this->fetch();
    }

    public function doedit()
    {
        $role = Db::name('role_user')->where(['user_id'=>cmf_get_current_admin_id()])->value('role_id');
        if($role == 2 || $role == 3){
            $this->error('无权限操作');
        }
        $data = $this->request->param();
        $files = request()->file('img');
        $id = $data['id'];
        unset($data['id']);
        $check = Db::name('contact')->where(['id' => $id])->find();

        // 处理要删除的图片
        $removeImg = isset($data['remove_img']) ? $data['remove_img'] : [];
        unset($data['remove_img']);

        // 处理保留的旧图片
        $oldImg = isset($data['old_img']) ? $data['old_img'] : [];
        unset($data['old_img']);

        // 处理图片
        if (!is_null($files) || !empty($removeImg)) {
            $kps = [];
            // 如果有旧图片，先添加到数组中
            if (!empty($oldImg)) {
                // 处理旧图片，去除域名只保留路径
                foreach ($oldImg as $img) {
                    if (!empty($img)) {
                        // 如果图片路径包含域名，只保留路径部分
                        if (strpos($img, 'http://') === 0 || strpos($img, 'https://') === 0) {
                            $parsedUrl = parse_url($img);
                            $kps[] = $parsedUrl['path'];
                        } else {
                            $kps[] = $img;
                        }
                    }
                }
            } else if (!empty($check['img']) && empty($removeImg)) {
                // 如果没有指定旧图片但数据库中有图片且没有要删除的图片，则使用数据库中的图片
                $imgArray = explode(',', $check['img']);
                foreach ($imgArray as $img) {
                    if (!empty($img)) {
                        $kps[] = $img;
                    }
                }
            }

            // 处理新上传的图片
            if (!is_null($files)) {
                // 为每个文件创建唯一目录，而不是每批次
                foreach ($files as $file) {
                    // 为每个文件创建唯一目录
                    $uploadDir = 'uploads/' . date('YmdHis') . mt_rand(1000, 9999) . '_' . mt_rand(1000, 9999);
                    // 确保目录存在
                    if (!file_exists(CMF_ROOT . 'public/' . $uploadDir)) {
                        mkdir(CMF_ROOT . 'public/' . $uploadDir, 0777, true);
                    }
                    
                    // 生成唯一文件名
                    $extension = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);
                    $newFilename = md5(uniqid(mt_rand(), true)) . '.' . $extension;
                    
                    // 直接使用PHP的move_uploaded_file函数
                    $tmpName = $file->getInfo('tmp_name');
                    $destPath = CMF_ROOT . 'public/' . $uploadDir . '/' . $newFilename;
                    
                    if (move_uploaded_file($tmpName, $destPath)) {
                        $kps[] = '/' . $uploadDir . '/' . $newFilename;
                    } else {
                        $this->error('文件上传失败');
                    }
                }
            }

            $data['img'] = implode(',', $kps);
        }

        $data['createTime'] = time();
        $res = Db::name('contact')->where(['id' => $id])->update($data);
        if (!$res) {
            $this->error('操作失败');
        }
        $this->success('操作成功');
    }

    public function search()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $where = [];
        if (!empty($data['status'])) {
            $where['status'] = $data['status'];
        }
        $res = Db::name('contact')->where(['eid' => $id])->where($where)->order('createTime desc')->select()->toArray();
        foreach ($res as $k => &$v) {
            $v['img'] = 'http://' . $_SERVER['SERVER_NAME'] . $v['img'];
        }
        $this->assign('res', $res);
        $this->assign('id', $id);
        return $this->fetch('index');

    }
}